package pl.wroc.pwr.docs.repos.embedded.server;

import java.net.URL;
import java.security.ProtectionDomain;

import org.eclipse.jetty.annotations.AnnotationConfiguration;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.Configuration;
import org.eclipse.jetty.webapp.WebAppContext;
import org.eclipse.jetty.webapp.WebInfConfiguration;
import org.eclipse.jetty.webapp.WebXmlConfiguration;

/**
 * Wbudowany serwer http i kontener serwletów. Jeden serwer na aplikację.
 */

public class WebServer {
	private Server server;
	private static WebServer instance;
	private static int port = 8080;
	private static String dbFilepath;
	
	private WebServer(int port) {
		WebAppContext context = new WebAppContext();
		
		ProtectionDomain protectionDomain = WebServer.class.getProtectionDomain();
		URL location = protectionDomain.getCodeSource().getLocation();
		
		context.setConfigurations(new Configuration[] {
				new WebInfConfiguration(),
				new WebXmlConfiguration(),
                new AnnotationConfiguration(), 
                });
		context.setWar(location.toExternalForm());
		context.setDescriptor("WEB-INF/web.xml");
		if(dbFilepath != null){
			context.setInitParameter("db.url.override", "jdbc:h2:file:" + dbFilepath);
		}
		server = new Server(port);
		server.setHandler(context);
	}

	public static void setPort(int port){
		WebServer.port = port;
	}
	
	public static void setDatabase(String filepath){
		dbFilepath = filepath;
	}
	
	public static WebServer get(){
		if(instance == null){
			instance = new WebServer(port);
		}	
		return instance;
	}
	
	public static int getPort(){
		return port;
	}
	
	public void start() throws Exception {
		server.start();
	}
	
	public void stop() throws Exception{
		server.stop();
	}
}
